# -*- coding: UTF-8 -*-
"""
@author:zhangxing
@file:dd_warning_msg.py
@time:2021/01/08
"""
import re

import requests
import json
import base64
import hashlib
import hmac
import time
import urllib

headers = {'Content-Type': 'application/json;charset=utf-8'}
# atmobile_list = ["18852513357", "17366203236"]
spider_list_zhangxing = ["17366203236",
                         '广东省全国公共资源交易平台',
                         '广州公共资源交易中心',
                         ]
spider_list_wubailong = ["18852513357",

                         ]
spider_list_madongdong = ["13089726217",
                          '山东省交通建设市场监管公共服务平台',
                          '金蝉电子招投标综合交易平台',
                          '山西省公共资源交易平台']

spider_list = [
    spider_list_zhangxing,
    spider_list_wubailong,
    spider_list_madongdong
]


def ddmsgsend(text):
    spider_name, atmobile = '', ''
    try:
        spider_name = re.findall('【(.*?)】', text)[0]
    except:
        pass
    for index, spiders in enumerate(spider_list):
        if spider_name in spiders:
            atmobile = spiders[index]
    api_url = "https://oapi.dingtalk.com/robot/send?access_token=d3d4ae47b3e0545f510c71e81d71368bfde007641335ae12e85d8e13d395fb99"
    # api_url = get_url()
    json_text = {
        "msgtype": "text",
        "at": {
            "atMobiles": atmobile,
            "isAtAll": False
        },
        "text": {
            "content": text
        }
    }
    if "采集数据为0" not in text:
        del json_text['at']
    return requests.post(api_url, json.dumps(json_text), headers=headers).content.decode("utf8")


if __name__ == '__main__':
    text = "采集数据为0采集0报警(测试) \n" \
           "众能联合\n" \
           "工程信息知识库\033[31m it should be red\033[0m项目；"
    res = ddmsgsend(text)
    print(res)

# TOKEN = "d3d4ae47b3e0545f510c71e81d71368bfde007641335ae12e85d8e13d395fb99"
# SECRET = "钉钉机器人中可以获取到"
# 加密所需接口
# def get_url():
#     # 按官方的要求进行加密，并且生成完成的链接，官方是py2，此处是py3
#     # 钉钉官方要求，请求的url中必须携带三个参数，access_token， timestamp，sign(签名是由secret加密而来)
#     timestamp = round(time.time() * 1000)
#     secret_enc = secret.encode('utf-8')
#     string_to_sign = '{}\n{}'.format(timestamp, SECRET)
#     string_to_sign_enc = string_to_sign.encode('utf-8')
#     hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
#     sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
#
#     # 完整的url
#     # api_url = "https://oapi.dingtalk.com/robot/send?access_token={}&timestamp={}&sign={}".format(TOKEN, timestamp, sign)
#     api_url = "https://oapi.dingtalk.com/robot/send?access_token={}".format(TOKEN)
#     return api_url
